package com.example.daxiguaforharmony.utils;

import com.example.daxiguaforharmony.ResourceTable;
import com.example.daxiguaforharmony.game.core.renderers.LabelAtlas;
import ohos.agp.components.Button;
import ohos.agp.components.Component;
import ohos.agp.components.Image;
import ohos.agp.components.element.PixelMapElement;
import ohos.agp.render.Canvas;
import ohos.agp.render.Paint;
import ohos.agp.render.Picture;
import ohos.agp.render.PixelMapHolder;
import ohos.app.Context;
import ohos.global.resource.*;
import ohos.media.image.ImageSource;
import ohos.media.image.PixelMap;

import java.io.IOException;
import java.io.InputStream;

public class ImageUtil {
    Resource btnBgResource=null;
    Image image;

    public static void mirrorImage(Image imageBj, PixelMap pixelMap, String str,Paint paint,int itemWidth,int itemHeight,int itemSzie) {
        System.out.println("mirrorImage starting ======");
        /**
         * 缩放指数 原始的图片的缩放大小
         * 数值为原始图片的宽度（pixelMap.getImageInfo().size.width）除以屏幕的宽度（windowHandler.getWindowWidth()） 的倒数
         */
        //float ratio = (float) DeviceUtils.getScreenWidth(this)/(float) pixelMap.getImageInfo().size.width;

        imageBj.addDrawTask(
                new Component.DrawTask() {

                    @Override
                    public void onDraw(Component component, Canvas canvas) {
                        PixelMapHolder pmh = new PixelMapHolder(pixelMap);
                        System.out.println("mirrorImage starting ======"+str);

                        LabelAtlas label = new LabelAtlas(pmh, itemWidth, itemHeight,itemSzie);
                        label.text = str;
                        label.x = 30f;
                        label.y = 30f;
                        label.spacingX = -25;
                        label.render(canvas, paint);

                        //canvas.drawPixelMapHolderRect(pmh,rectFloat1,rectFloat2,paint);
                        //canvas.drawPixelMapHolder(pmh,0,0, new Paint());
                        System.out.println("mirrorImage end ======"+str);
                    }
                });

        //为component增加drawtask方法
        //component.addDrawTask(drawTask);
    }

    public static String getGameTip(int score, Context context)
    {
        double randValue = 50.00;
        if (score > 2000) {
            randValue = (double)((95 + Math.random() * 5));
        } else if (score > 1600) {
            randValue = (double)((90 + Math.random() * 5));
        } else if (score > 1400) {
            randValue = (double)((85 + Math.random() * 5));
        } else if (score > 1200) {
            randValue = (double)((80 + Math.random() * 5));
        } else if (score > 1000) {
            randValue = (double)((70 + Math.random() * 5));
        } else if (score > 800) {
            randValue = (double)((60 + Math.random() * 10));
        } else {
            randValue = (double)((50 + Math.random() * 10));
        }
        //DecimalFormat df2  = new DecimalFormat("###.00");//这样为保持2位

        randValue = Math.round(randValue);;
        String text = "击败全世界"+randValue+"%的小伙伴!";


//        DbKvManager dbKvManager = new DbKvManager(context);
//        //DbKvManager dbKvManager = DbKvManager.getDbKvManager();
//        //dbKvManager.init(context);
//
//        String score_high = dbKvManager.read("score_high");
//        if(score_high != null && !score_high.isEmpty())
//        {
//            if(score > Integer.parseInt(score_high))
//            {
//                dbKvManager.write("score_high",Integer.toString(score));
//            }
//        }
//        else
//        {
//            dbKvManager.write("score_high",Integer.toString(score));
//        }


        return text;

    }

    public PixelMap getPixelMapFromResource(int resourceId,Context context) {
        System.out.println("getPixelMapFromResource is starting=====");
        InputStream inputStream = null;
        try {
            // 创建图像数据源ImageSource对象
            System.out.println("inputStream is start======");
            inputStream = context.getResourceManager().getResource(resourceId);
            if(inputStream != null)
            {
                System.out.println("inputStream is ok========");
            }
            else
            {
                System.out.println("inputStream is null==========");
            }
            ImageSource.SourceOptions srcOpts = new ImageSource.SourceOptions();
            srcOpts.formatHint = "image/png";
            ImageSource imageSource = ImageSource.create(inputStream, srcOpts);


            // 设置图片参数
            ImageSource.DecodingOptions decodingOptions = new ImageSource.DecodingOptions();
            return imageSource.createPixelmap(decodingOptions);
        } catch (IOException e) {
            //HiLog.info(LABEL_LOG, "IOException");
            System.out.println("IOException==="+e.getMessage());
        } catch (NotExistException e) {
            //HiLog.info(LABEL_LOG, "NotExistException");
            System.out.println("NotExistException==="+e.getMessage());
        } finally {
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    //HiLog.info(LABEL_LOG, "inputStream IOException");
                    System.out.println("inputStream IOException==="+e.getMessage());
                }
            }
        }
        System.out.println("getPixelMapFromResource is back null=========");
        return null;
    }

    public void mirrorImage(PixelMap pixelMap,Image image) {
        System.out.println("mirrorImage starting ======");
        image.addDrawTask(
                new Component.DrawTask() {
                    @Override
                    public void onDraw(Component component, Canvas canvas) {
                        PixelMapHolder pmh = new PixelMapHolder(pixelMap);
                        //canvas.scale(10,30);
                        canvas.drawPixelMapHolder(
                                pmh,
                                0,
                                0,
                                new Paint());
                    }
                });
    }

    public void setImageBtn(Button btnFind, ResourceManager res)
    {
                try {
                    //获取Media文件夹中的图片资源
            btnBgResource=res.getResource(ResourceTable.Media_qianyi);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (NotExistException e) {
            e.printStackTrace();
        }
        //按钮同理
        PixelMapElement pixBtnBg=new PixelMapElement(btnBgResource);
        //Button btnBg=(Button)findComponentById(ResourceTable.Id_btnBg);
        btnFind.setBackground(pixBtnBg);
    }

    public Image readRawToImage(String picName,ResourceManager res) throws IOException {
        //RawFileDescriptor filDescriptor = res.getRawFileEntry("resources/rawfile/dayu.mp3").openRawFileDescriptor();
        RawFileEntry fileEntry=res.getRawFileEntry("resources/base/media/111.jpg");
        //获取文件大小
        int fileSize=(int)fileEntry.openRawFileDescriptor().getFileSize();
        //定义读取文件的字节
        byte[] fileDatas=new byte[fileSize];
        //读取文件字节
        fileEntry.openRawFile().read(fileDatas);
        // 创建图像数据源ImageSource对象
        ImageSource.SourceOptions sourceOptions = new ImageSource.SourceOptions();
        //sourceOptions.formatHint="image/png";
        ImageSource imageSource = ImageSource.create(fileDatas,sourceOptions);
        PixelMap pixelMap = imageSource.createPixelmap(new ImageSource.DecodingOptions());
        image.setPixelMap(pixelMap);
        return image;
    }

    public void rotate(Canvas canvas, Picture picture)
    {
        //以图片中心为旋转中心，旋转90度
        canvas.rotate(90 , picture.getWidth()/2 , picture.getWidth()/2);
    }


}
